
import random

def monty_hall_simulation(num_trials=1000000):

    switch_wins = 0   # 换门获胜次数
    stay_wins = 0     # 不换门获胜次数

    for _ in range(num_trials):

        # 随机生成奖品位置（0, 1, 2）
        prize_door = random.randint(0, 2)

        # 参赛者初始选择
        initial_choice = random.randint(0, 2)

        # 主持人剩余可选的门(无奖品且未被选的门)
        remaining_doors = [door for door in [0, 1, 2] if door != initial_choice and door != prize_door]

        # 如果参赛者开始选对了（剩余有2个门），主持人可随机开一扇
        # 如果开始选错了（剩余只有1个门），主持人只能开这扇门
        opened_door = random.choice(remaining_doors) if len(remaining_doors) > 1 else remaining_doors[0]

        # 换门：选择既不是初始选择也不是主持人打开的门
        final_choice_switch = [door for door in [0, 1, 2] if door != initial_choice and door != opened_door][0]

        # 统计结果
        if final_choice_switch == prize_door:
            switch_wins += 1
        #endif

        if initial_choice == prize_door:
            stay_wins += 1
        #endif

    #next

    print(f"  模拟次数: {num_trials}")
    print(f"  换门胜率: {switch_wins*100 / num_trials:.2f} %")
    print(f"不换门胜率: {stay_wins*100 / num_trials:.2f} %")

#end def

# -----------------------------------------------------------------------------
# Main Program
# -----------------------------------------------------------------------------
if __name__ == '__main__':

    # 运行模拟（默认10万次）
    monty_hall_simulation()